package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.Basic.util.AjaxResult;
import cn.itsource.pethome.Basic.util.RedisUtils;
import cn.itsource.pethome.Basic.util.StrUtils;
import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.service.IUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @PostMapping("/checkPhone")
    public AjaxResult checkPhone(@RequestBody Map<String,String> checkPhone){
        return userService.checkPhone(checkPhone.get("phone"));

    }

    /**
     * 注册
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"注册失败");
        }
    }
    /*@PostMapping("/emailRegister")
    public AjaxResult emailRegister(@RequestBody UserDto userDto){
        try {
            userService.emailRegister(userDto);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"注册失败");
        }
    }*/
    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user){
        try {
            //获取登录用户
            User loginUser = userService.login(user.getUsername(), user.getPassword());
            //讲对象转为json字符串
            String jsonString = JSON.toJSONString(loginUser);
            //获取令牌
            String token = UUID.randomUUID().toString();
            //登录对象存到redis中
            RedisUtils.INSTANCE.set(token,jsonString,30*60);
            //将令牌和对象封装到map返回到前端（欢迎xx登录）
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("loginUser",loginUser);
            return new AjaxResult().setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }
    public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        user.setUsername("Aa");
        user.setPassword("123");
        user.setAge(22);

        String string = JSON.toJSONString(user);
        System.out.println(string);
    }
}
